<?php

namespace App\Models;

use App\Models\Scopes\ActiveScope;
use App\Traits\Presenter;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Overtrue\Pinyin\Pinyin;

class Video extends Model
{
    use Presenter;

    protected $fillable = [
        'title',
        'description',
        'abbr',
        'picture',
        'videos',
        'visits',
        'playback',
        'like',
        'score',
        'vip',
        'show',
        'seo_keywords',
        'seo_description',
    ];

    protected $casts = [
        'visits' => 'int',
        'playback' => 'int',
        'like' => 'int',
        'score' => 'int',
        'vip' => 'bool',
        'show' => 'bool',
        'videos' => 'collection',
    ];

    protected $attributes = [
        'visits' => 0,
        'playback' => 0,
        'score' => 0,
        'like' => 0,
        'vip' => false,
        'show' => true,
    ];

    /**
     * 自动观察 视频更新
     */
    protected static function booted(): void
    {
        static::addGlobalScope(new ActiveScope);

        static::saving(function (Video $video) {
            if ($video->isDirty('title')) {
                $video->abbr = Pinyin::abbr($video->title, 'none')->join('');
            }

            if ($video->isDirty('videos')) {
                $video->videos = $video->videos?->map(fn (array $arr) => empty($arr['fields']['path'])
                    ? $video->getOriginal('videos')->firstWhere('fields.id', $arr['fields']['id'])
                    : $arr
                );
            }
        });
    }

    /**
     * 演员
     */
    public function actors(): BelongsToMany
    {
        return $this->belongsToMany(Actor::class);
    }

    /**
     * 专题
     */
    public function specials(): BelongsToMany
    {
        return $this->belongsToMany(Special::class);
    }

    /**
     * 收藏
     */
    public function favorites(): MorphMany
    {
        return $this->morphMany(Favorite::class, 'favorite');
    }

    /**
     * 分类
     */
    public function categories(): BelongsToMany
    {
        return $this->belongsToMany(Category::class);
    }

    /**
     * 标签
     */
    public function tags(): BelongsToMany
    {
        return $this->belongsToMany(Tag::class);
    }
}
